package com.wash.shoes.domain.mtbusy;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.lop.open.api.sdk.DefaultDomainApiClient;
import com.lop.open.api.sdk.LopException;
import com.lop.open.api.sdk.domain.ECAP.CommonModifyCancelOrderApi.commonModifyOrderV1.CommonModifyCancelOrderRequest;
import com.lop.open.api.sdk.plugin.LopPlugin;
import com.lop.open.api.sdk.plugin.factory.OAuth2PluginFactory;
import com.lop.open.api.sdk.request.ECAP.EcapV1OrdersModifyLopRequest;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersModifyLopResponse;
import com.meituan.sdk.MeituanResponse;
import com.meituan.sdk.model.ddzh.yuding.changeresultcallback.ChangeresultcallbackRequest;
import com.meituan.sdk.model.ddzh.yuding.changeresultcallback.ChangeresultcallbackResponse;
import com.wash.shoes.domain.dto.ReReserveDto;
import com.wash.shoes.domain.vo.MtPushMessage;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.exception.WashException;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author lijianguo
 * @Date 16/09/2024
 * 改约提交，美团的改约提交，就是修改物流信息的时间
 **/
@Log4j2
@Component
public class Mt5810015Busy extends AbstractMtCallback {


    @Override
    public MtCallbackEnum getType() {
        return MtCallbackEnum.MT_5810015;
    }

    @Override
    public Integer processBusy(MtPushMessage message, String token, String developerId) {

        ReReserveDto reReserveDto = JSONObject.parseObject(message.getMessage(), ReReserveDto.class);
        try {
            OrderPo orderPo = processBefore(message, reReserveDto);
            log.info("改约处理成功，订单号: {}, orderId: {}", orderPo.getOrderNo(), reReserveDto.getOrderId());
            changeResultantBack(reReserveDto.getOrderId(), 2, 200, getToken58(message.getOpBizCode()), developerId);

        } catch (Exception e) {
            log.error("改约处理失败，订单ID: {}, 错误信息: {}", reReserveDto.getOrderId(), e.getMessage(), e);
            changeResultantBack(reReserveDto.getOrderId(), 3, 808, getToken58(message.getOpBizCode()), developerId);
            throw new WashException("该有处理订单失败: " + e.getMessage(), e);
        }
        return 1;
    }

    /**
     * 返回给美团改约结果
     *
     * @param orderId
     * @param bookStatus
     * @param code
     * @param token
     */
    private void changeResultantBack(String orderId, int bookStatus, int code, String token, String developerId) {

        try {
            ChangeresultcallbackRequest request = new ChangeresultcallbackRequest();
            request.setReserveOrderId(Long.valueOf(orderId));
            request.setChangeOrderResult(bookStatus);
            request.setCode(code);
            MeituanResponse<ChangeresultcallbackResponse> mtResponse = MtAllClient.getClient(developerId).invokeApi(request, token);
            log.info("mt changeresultcallback request is {}", JSONObject.toJSONString(request));
            log.info("mt changeresultcallback response is {}", JSONObject.toJSONString(mtResponse));
            if (!mtResponse.isSuccess()) {
                throw new WashException(mtResponse.getMsg());
            }
        } catch (Exception e) {
            log.error(e);
        }
    }


    /**
     * 改约结果修改物流信息
     *
     * @param message
     * @param reReserveDto
     * @return
     */
    private OrderPo processBefore(MtPushMessage message, ReReserveDto reReserveDto) {
        OrderPo orderPo;
        try {
            // 校验是否存在订单
            orderPo = Optional.ofNullable(orderService.getByMtOrderId(reReserveDto.getOrderId()))
                    .orElseThrow(() -> new RuntimeException("订单不存在: " + reReserveDto.getOrderId()));

            // 校验是否存在物流信息
            OrderTransportPo orderTransportPo = Optional.ofNullable(orderTransportService.getOneByOrderId(orderPo.getId()))
                    .orElseThrow(() -> new RuntimeException("物流信息不存在，订单ID: " + orderPo.getId()));

            // 创建修改预约时间的请求
            EcapV1OrdersModifyLopRequest request = new EcapV1OrdersModifyLopRequest();
            CommonModifyCancelOrderRequest commonRequest = new CommonModifyCancelOrderRequest();
            request.setRequest(commonRequest);

            // 解析预约时间并转换为秒
            DateTime dateTime = DateUtil.parse(reReserveDto.getReserveBegintime(), "yyyy-MM-dd HH:mm");
            long seconds = dateTime.toInstant().getEpochSecond();

            // 设置请求参数
            commonRequest.setOrderOrigin(Integer.parseInt(orderTransportPo.getOrderOrigin()));
            commonRequest.setOrderCode(orderTransportPo.getOrderCode());
            commonRequest.setWaybillCode(orderTransportPo.getWayBillCode());
            commonRequest.setPickupStartTime(seconds * 1000L);
            commonRequest.setPickupEndTime((seconds + 7200) * 1000L); // 预约时间加2小时
            commonRequest.setCustomerCode(jdProperty.getCustomerCode());

            // 创建API客户端并添加LopPlugin
            DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
            LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
            request.addLopPlugin(lopPlugin);

            // 执行请求
            EcapV1OrdersModifyLopResponse response = client.execute(request);
            log.info("修改预约时间 request 参数为: {} ", JSONObject.toJSONString(request));
            log.info("修改预约时间 response 参数为: {} ", JSONObject.toJSONString(response));

        } catch (LopException e) {
            log.error("预约时间修改失败: ", e);
            throw new RuntimeException("预约时间修改失败: " + e.getMessage(), e);
        }
        return orderPo;
    }
}
